// tools

// weex 全局环境变量
var wx = (typeof WXEnvironment === 'object' && WXEnvironment.weexVersion) ? WXEnvironment : undefined
// window 全局window，针对h5
var win = typeof window === 'object' && window.addEventListener ? window : undefined
// 判断是否是h5容器
var isH5 = !wx || (wx.platform === 'Web')

function $safetyCall$ (fn, args, defaultValue) {
  if (typeof fn !== 'function') return defaultValue
  try {
    return fn.apply(this, args)
  } catch (ex) {
    return defaultValue
  }
}

function $filterByRule$ (str, rule) {
  if (!str) return ''
  if (!rule) return str
  // eslint-disable-next-line one-var
  var that = this,
    type = that.T(rule)
  if (type === 'Function') {
    return $safetyCall$(rule, [str], str)
  } else if (type === 'Array') {
    this.each(rule, function (r) {
      str = that.$filterByRule$(str, r)
    })
    return str
  } else if (type === 'Object') {
    return str.replace(rule.rule, rule.target || '')
  } else {
    return str.replace(rule, '')
  }
}

export const agentTools = {
  wx,
  win,
  isH5,
  // 设备长宽
  getSr: function () {
    return isH5
      ? (screen.width + 'x' + screen.height)
      : (wx.deviceWidth + 'x' + wx.deviceHeight)
  },
  // 获取页面url
  getH5Page: function (ignoreRule, ignoreUrlCase) {
    var loc = location
    var pUrl = loc.host + loc.pathname

    return $filterByRule$(ignoreUrlCase ? pUrl.toLowerCase() : pUrl, ignoreRule)
  }
}
